/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace DaveSexton.DocProject.Sandcastle.ContentManagement
{
	[Serializable]
	public class ContentItemCollection : Collection<ContentItem>
	{
		#region Public Properties
		#endregion

		#region Private / Protected
		private readonly ContentDocument document;
		private readonly bool manageDocument;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="ContentItemCollection" /> class.
		/// </summary>
		public ContentItemCollection()
		{
		}

		/// <summary>
		/// Constructs a new instance of the <see cref="ContentItemCollection" /> class.
		/// </summary>
		public ContentItemCollection(ContentDocument document)
		{
			if (document == null)
				throw new ArgumentNullException("document");

			this.document = document;
			manageDocument = true;
		}

		/// <summary>
		/// Constructs a new instance of the <see cref="ContentItemCollection" /> class.
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
		public ContentItemCollection(ContentItemCollection clone)
		{
			if (clone == null)
				throw new ArgumentNullException("clone");

			document = clone.document;
			manageDocument = clone.manageDocument;

			foreach (ContentItem item in clone)
				Add(item);
		}
		#endregion

		#region Methods
		protected override void ClearItems()
		{
			if (manageDocument)
				foreach (ContentItem item in this)
					item.Document = null;

			base.ClearItems();
		}

		protected override void RemoveItem(int index)
		{
			if (manageDocument)
				this[index].Document = null;

			base.RemoveItem(index);
		}

		protected override void InsertItem(int index, ContentItem item)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			if (manageDocument)
				item.Document = document;

			base.InsertItem(index, item);
		}

		protected override void SetItem(int index, ContentItem item)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			if (manageDocument)
			{
				ContentItem current = this[index];

				current.Document = null;
				item.Document = document;
			}

			base.SetItem(index, item);
		}
		#endregion
	}
}
